import 'package:awak/common/db/db_helper.dart';
import 'package:awak/common/models/favorite.dart';
import 'package:awak/common/models/content.dart';

class FavoriteRepository {
  // 添加收藏
  Future<int> addFavorite(Favorite favorite) async {
    final db = await DBHelper.database;
    return await db.insert('favorite', favorite.toMap());
  }

  // 移除收藏
  Future<int> removeFavorite(int userId, int contentId) async {
    final db = await DBHelper.database;
    return await db.delete(
      'favorite',
      where: 'userId = ? AND contentId = ?',
      whereArgs: [userId, contentId],
    );
  }

  // 检查是否已收藏
  Future<bool> isFavorited(int userId, int contentId) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'favorite',
      where: 'userId = ? AND contentId = ?',
      whereArgs: [userId, contentId],
    );
    return res.isNotEmpty;
  }

  // 获取用户的所有收藏
  Future<List<Favorite>> getFavoritesByUserId(int userId) async {
    final db = await DBHelper.database;
    final res = await db.query(
      'favorite',
      where: 'userId = ?',
      whereArgs: [userId],
      orderBy: 'createdAt DESC',
    );
    return res.map((e) => Favorite.fromMap(e)).toList();
  }

  // 获取用户收藏的内容列表
  Future<List<Content>> getFavoriteContentsByUserId(int userId) async {
    final db = await DBHelper.database;
    final res = await db.rawQuery('''
      SELECT c.* FROM content c
      INNER JOIN favorite f ON c.id = f.contentId
      WHERE f.userId = ?
      ORDER BY f.createdAt DESC
    ''', [userId]);
    return res.map((e) => Content.fromMap(e)).toList();
  }

  // 获取内容的收藏数量
  Future<int> getFavoriteCountByContentId(int contentId) async {
    final db = await DBHelper.database;
    final res = await db.rawQuery(
      'SELECT COUNT(*) as count FROM favorite WHERE contentId = ?',
      [contentId],
    );
    return res.first['count'] as int;
  }

  // 获取所有收藏
  Future<List<Favorite>> getAllFavorites() async {
    final db = await DBHelper.database;
    final res = await db.query('favorite', orderBy: 'createdAt DESC');
    return res.map((e) => Favorite.fromMap(e)).toList();
  }

  // 删除收藏
  Future<int> deleteFavorite(int id) async {
    final db = await DBHelper.database;
    return await db.delete('favorite', where: 'id = ?', whereArgs: [id]);
  }

  // 切换收藏状态
  Future<bool> toggleFavorite(int userId, int contentId) async {
    final isFav = await isFavorited(userId, contentId);
    if (isFav) {
      await removeFavorite(userId, contentId);
      return false;
    } else {
      final favorite = Favorite(
        userId: userId,
        contentId: contentId,
        createdAt: DateTime.now(),
      );
      await addFavorite(favorite);
      return true;
    }
  }
}
